<template>
  <a-modal
    :destroy-on-close="true"
    :visible="visible"
    :title="title"
    :confirm-loading="tableLoading"
    width="600px"
    @cancel="handleClose"
    @ok="handleSubmit"
  >
    <a-form layout="inline" :model="params" @submit="handleSearch">
      <a-form-item label="表名称">
        <a-input v-model:value="params.tableName" placeholder="请输入表名称" />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" :loading="tableLoading" html-type="submit">
          <template #icon><SearchOutlined /></template>
          <span v-if="!tableLoading">搜索</span>
          <span v-else>搜索中...</span>
        </a-button>
      </a-form-item>
    </a-form>

    <a-table
      :loading="tableLoading"
      :row-selection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange
      }"
      :columns="tableColumns"
      :data-source="tableDataSource"
      :pagination="pageInfo"
      row-key="tableName"
      size="middle"
      @change="handlePageChange"
    >
    </a-table>
  </a-modal>
</template>

<script name="ToolGenImport" lang="ts" setup>
import { getDBPage, importTable } from "@/api/tool/gen";
const emit = defineEmits(["reload"]);
const visible = ref(false);
const title = ref("导入");

//搜索表单
const params = reactive({
  tableName: ""
});

//表格
const tableColumns = ref<TableColumn[]>([
  {
    key: "tableName",
    dataIndex: "tableName",
    title: "表名称"
  },
  {
    key: "tableComment",
    dataIndex: "tableComment",
    title: "表描述"
  }
]);

const { tableLoading, pageInfo, tableDataSource, handleLoadData, handlePageChange, handleSearch } = useTablePage(
  params,
  getDBPage
);

//表格选择
const { selectedRowKeys, onSelectChange } = useTableSelect();

const show = () => {
  handleLoadData();
  selectedRowKeys.value = [];
  visible.value = true;
};

const handleClose = () => {
  visible.value = false;
};

const handleSubmit = () => {
  if (selectedRowKeys.value.length > 0) {
    importTable(selectedRowKeys.value)
      .then(() => {
        antdMessage.success("导入成功");
        emit("reload");
        handleLoadData();
        handleClose();
      })
      .finally(() => {
        tableLoading.value = false;
      });
  } else {
    handleClose();
  }
};

defineExpose({ show });
</script>

<style lang="less" scoped>
.ant-table-wrapper{
  margin-top: 20px;
}
</style>
